/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.almac;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.*;
import dp1.titandevelop.titano.service.AlmacenService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.service.ZonaService;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
/**
 *
 * @author Yulian
 */
public class ModulosT_ALM_AlmNuevo extends javax.swing.JInternalFrame {

    private  List<Producto> productos ;
    private  List<Integer> idproductos;
    private  List<Integer> capacidades ;
    private  List<Zona> lista;
    
    private Mensajes sms = new Mensajes();
    
    public void addProducto(Producto e){
        this.productos.add(e);
        this.idproductos.add(e.getIdproducto());
    }
    public void addCapacidad(int e){
        this.capacidades.add(e);
    }
    public void habilitaBotones(){
        this.btnEliminar.setEnabled(true);
    }
    private void inhabilitaBotones(){
        this.btnEliminar.setEnabled(false);
    }
    
    public void RefreshTable() {
        AbstractTableModel aux = (AbstractTableModel)tblCapacidades.getModel();
        aux.fireTableDataChanged();
    }
    
    private void addList (List<Zona> lista){
        
        for(int i=0;i<lista.size();i++){
            this.cboxZona.addItem(lista.get(i).getDescripcion());
        }
    }
    //Modelo de tabla de almacenes
    private AbstractTableModel modeloTabla = new AbstractTableModel()  {  
        
        @Override
        public int getRowCount() {
            return capacidades.size(); // cuantos registros (filas)
        }      
        
        @Override
        public int getColumnCount() {
            return 2; // cuantas columnas
        }  
        
        String [] titles = {"Productos", "Capacidad"};
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }        
          
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            Producto prod = productos.get(rowIndex);
            int cap = capacidades.get(rowIndex);
            switch(columnIndex){
                case 0: res = prod.getDescripcion(); break;
                case 1: res = cap; break;
            }
            return res;
        }  
    };
    
    public ModulosT_ALM_AlmNuevo() {
        initComponents();        
        this.productos=new ArrayList<Producto>();
        this.idproductos = new ArrayList<Integer>();
        this.capacidades = new ArrayList<Integer>();
        tblCapacidades.setModel(modeloTabla);
        this.inhabilitaBotones();
        
        ZonaService serv = new ZonaService();
        lista = serv.buscar();//Obtengos los productos de la bd
        addList(lista);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCapacidades = new javax.swing.JTable();
        btnEliminar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cboxZona = new javax.swing.JComboBox();
        btnAsignar = new javax.swing.JButton();

        setResizable(true);
        setTitle("Nuevo Almacén");

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Registros de Capacidad"));

        tblCapacidades.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Capacidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tblCapacidades.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblCapacidadesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblCapacidades);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminar)
                .addGap(8, 8, 8))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnEliminar)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8))
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Almacén"));

        jLabel1.setText("Descripción");

        jLabel3.setText("Ubicación");

        jLabel2.setText("Zona");

        cboxZona.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));

        btnAsignar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnAsignar.setToolTipText("Asignar Producto");
        btnAsignar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAsignarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtDescripcion)
                            .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(cboxZona, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAsignar)
                        .addGap(8, 8, 8))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cboxZona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnAsignar))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(1, 1, 1)
                        .addComponent(btnCancelar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(8, 8, 8))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(8, 8, 8))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(1, 1, 1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAsignarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAsignarActionPerformed
        Frame f = JOptionPane.getFrameForComponent(this);
        ModulosT_ALM_AlmNuevoAsignacion dialog = new ModulosT_ALM_AlmNuevoAsignacion(f,true);
        dialog.setVisible(true);
        

//        ventanaAsignacion = new ModulosT_ALM_AlmNuevoAsig(productos,capacidades);
//        this.getParent().add(ventanaAsignacion);
//        ventanaAsignacion.setVisible(true);
    }//GEN-LAST:event_btnAsignarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        
        ModulosT_ALM.menuAdmAlm= new ModulosT_ALM_AdmAlm();
        this.getParent().add( ModulosT_ALM.menuAdmAlm);
        
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ModulosT_ALM.menuAdmAlm.getSize();
        ModulosT_ALM.menuAdmAlm.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height)/4 );        
        ModulosT_ALM.menuAdmAlm.show();
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        
        ValidacionService val = new ValidacionService();
        
        if(!val.esVacio(txtDescripcion)&&!val.esVacio(txtDireccion)&&!val.esCBoxVacio(cboxZona)){
            AlmacenService serv = new AlmacenService();
            if(capacidades.size()>0){
                try {
                    
                    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    serv.insertar(lista.get(cboxZona.getSelectedIndex()-1).getIdzona(),txtDescripcion.getText(),txtDireccion.getText(),idproductos,capacidades);
                    this.setCursor(Cursor.getDefaultCursor());
                    
                    JOptionPane.showInternalMessageDialog(this.getRootPane(), sms.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);

                   } catch(Exception e) {                          
                       JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
                   }

            }
            else{
                try {
                    
                    serv.insertar(lista.get(cboxZona.getSelectedIndex()-1).getIdzona(),txtDescripcion.getText(),txtDireccion.getText());

                    JOptionPane.showInternalMessageDialog(this.getRootPane(), sms.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);

                   } catch(Exception e) {                          
                       JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
                   }
                
            }   
            
            ModulosT_ALM.menuAdmAlm = new ModulosT_ALM_AdmAlm();
            this.getParent().add( ModulosT_ALM.menuAdmAlm);
            Dimension desktopSize = this.getParent().getSize();
            Dimension jInternalFrameSize =  ModulosT_ALM.menuAdmAlm.getSize();
            ModulosT_ALM.menuAdmAlm.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                    (desktopSize.height - jInternalFrameSize.height)/4 );
            ModulosT_ALM.menuAdmAlm.show();

            this.dispose();
        }
        else{
            JOptionPane.showInternalMessageDialog(this.getRootPane(), sms.getCompletarCampos(),"Aviso",JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        this.productos.remove(this.tblCapacidades.getSelectedRow());
        this.capacidades.remove(this.tblCapacidades.getSelectedRow());
        this.RefreshTable();
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void tblCapacidadesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblCapacidadesMouseClicked
        if(evt.getClickCount()==1){
            this.habilitaBotones();
        }
    }//GEN-LAST:event_tblCapacidadesMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAsignar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cboxZona;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblCapacidades;
    private javax.swing.JTextField txtDescripcion;
    private javax.swing.JTextField txtDireccion;
    // End of variables declaration//GEN-END:variables
}
